import { useState, useLayoutEffect, useMemo } from "preact/hooks";
import { copyText, useThrottle } from "../utilities";
import { toast } from "../signals";
import { SquareArrowOutUpRight, Copy, RefreshCcw } from "lucide-preact";
import { settings } from "../settings";
import { types, buildUrl } from "./hitokoto";

const HitokotoCard = () => {
  const [data, setData] = useState({
    content: "正在获取...",
    from: "不知处",
    by: "无名氏",
    type: "g",
    uuid: "",
  });
  const [trigger, setTrigger] = useThrottle(0, 500);
  const caption = useMemo(
    () =>
      `——${data.by && data.by !== data.from ? data.by : ""}${data.from ? `《${data.from}》` : ""}`,
    [data],
  );
  useLayoutEffect(() => {
    fetch(buildUrl(settings.value.widget.hitokotoTypes))
      .then((resp) => resp.json())
      .then(({ hitokoto, from, from_who, type, uuid }) => {
        setData({
          content: hitokoto,
          from,
          by: from_who,
          type,
          uuid,
        });
      })
      .catch(() => toast("一言获取失败"));
  }, [trigger]);

  return (
    <div class="card w-69">
      <div class="card-body">
        <div class="card-actions place-items-center justify-between">
          <div class="badge badge-secondary">{types[data.type]}</div>
          <div class="*:btn-sm *:btn-circle *:btn-soft *:ml-2">
            <button
              type="button"
              class="btn btn-secondary"
              onClick={() => {
                window.open(`https://hitokoto.cn/?uuid=${data.uuid}`);
              }}
            >
              <SquareArrowOutUpRight class="size-4" />
            </button>
            <button
              type="button"
              class="btn btn-secondary"
              onClick={() => {
                copyText(`${data.content} ${caption}`);
              }}
            >
              <Copy class="size-4" />
            </button>
            <button
              type="button"
              class="btn btn-success"
              onClick={() => {
                setTrigger(trigger + 1);
              }}
            >
              <RefreshCcw class="size-4" />
            </button>
          </div>
        </div>
        <figure class="flex-col">
          <p class="text-xl font-bold">{data.content}</p>
          {settings.value.widget.hitokotoFrom ? (
            <figcaption class="text-md w-full text-end opacity-50">
              {caption}
            </figcaption>
          ) : (
            void 0
          )}
        </figure>
      </div>
    </div>
  );
};

export default HitokotoCard;
